package com.ecy.quadratic.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.text.util.Linkify;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.ecy.quadratic.R;
import com.ecy.quadratic.beans.Community;
import com.ecy.quadratic.beans.user.User;
import com.ecy.quadratic.manager.LikeManager;
import com.ecy.quadratic.manager.LoginManager;
import com.ecy.quadratic.photopicker.PhotoPreview;
import com.ecy.quadratic.reader.utils.FormatUtils;
import com.ecy.quadratic.reader.utils.ScreenUtils;
import com.ecy.quadratic.reader.view.TagColor;
import com.ecy.quadratic.reader.view.TagGroup;
import com.ecy.quadratic.ui.activity.CommunityDetailActivity;
import com.ecy.quadratic.ui.activity.LoginActivity;
import com.ecy.quadratic.widget.ScrollGridView;
import com.yuyh.easyadapter.glide.GlideCircleTransform;

import java.util.ArrayList;
import java.util.List;

public class CommunityListViewAdapter extends BaseAdapter {
    private LayoutInflater mInflater;
    private Context mContext;
    private List<Community> list;
    private int wh;
    private Fragment mFragment;
    private Activity mActivity;
    private LikeListener mLikeListener;

    public CommunityListViewAdapter(Fragment fragment, List<Community> list) {
        super();
        this.mInflater = LayoutInflater.from(fragment.getContext());
        this.mContext = fragment.getContext();
        mFragment = fragment;
        this.wh = (ScreenUtils.getScreenWidth() - ScreenUtils.dpToPxInt(36)) / 3;
        this.list = list;
    }

    public CommunityListViewAdapter(Activity activity, List<Community> list) {
        super();
        this.mInflater = LayoutInflater.from(activity);
        this.mContext = activity;
        mActivity = activity;
        this.wh = (ScreenUtils.getScreenWidth() - ScreenUtils.dpToPxInt(36)) / 3;
        this.list = list;
    }

    public void setLikeListener(LikeListener likeListener) {
        mLikeListener = likeListener;
    }

    public List<Community> getList() {
        return list;
    }

    public void setList(List<Community> list) {
        this.list = list;
    }

    @Override
    public int getCount() {
        return list == null ? 0 : list.size();
    }

    @Override
    public Object getItem(int arg0) {
        return list == null ? null : list.get(arg0);
    }

    public void updateCommentNum(String communityId) {
        for (int i = 0; i < getCount(); i++) {
            if (list.get(i).id.equals(communityId)) {
                list.get(i).commentnum++;
                notifyDataSetChanged();
            }
        }
    }

    @Override
    public long getItemId(int arg0) {
        return list == null ? null : arg0;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        if (list.size() == 0) {
            return null;
        }
        final ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.item_community, null);
            holder = new ViewHolder();
            holder.userPhotoIV = (ImageView) convertView.findViewById(R.id.community_user_portrait_iv);
            holder.nicknameTV = (TextView) convertView.findViewById(R.id.community_user_nickname_tv);
            holder.timeTV = (TextView) convertView.findViewById(R.id.community_item_time_tv);
            holder.contentTV = (TextView) convertView.findViewById(R.id.community_item_title_tv);
            holder.imagesGV = (ScrollGridView) convertView.findViewById(R.id.community_gridview);
            holder.tagGroup = (TagGroup) convertView.findViewById(R.id.tag_group);
            holder.likNumTV = (TextView) convertView.findViewById(R.id.community_item_like_tv);
            holder.commentNumTV = (TextView) convertView.findViewById(R.id.community_item_comment_tv);
            holder.bindAdapter();
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        final Community bean = list.get(position);

        String name = null, time = null, content = null, headpath = null;
        ArrayList<String> contentimages = null;
        if (bean != null) {
            if (bean.userBean != null) {
                name = bean.userBean.nickname;
                headpath = bean.userBean.portrait;
            }
            time = bean.createtime;
            content = bean.content;
            if (bean.imagesBean != null) {
                contentimages = bean.imagesBean;
            }
        }
        if (bean.tagsBean != null) {
            List<String> batch = bean.tagsBean;
            if (bean.tagsBean.size() > 4) {
                batch = bean.tagsBean.subList(0, 4);
            }

            List<TagColor> colors = TagColor.getRandomColors(batch.size());
            holder.tagGroup.setTags(colors, (String[]) batch.toArray(new String[batch.size()]));
            holder.tagGroup.setVisibility(View.VISIBLE);
        } else {
            holder.tagGroup.setVisibility(View.GONE);
        }

        if (bean.commentnum > 0) {
            holder.commentNumTV.setText("" + bean.commentnum);
        } else {
            holder.commentNumTV.setText(" ");
        }

        if (bean.likenum > 0) {
            holder.likNumTV.setText("" + bean.likenum);
        } else {
            holder.likNumTV.setText(" ");
        }

        if (bean.isLiked) {
            Drawable drawable = mContext.getResources().getDrawable(R.drawable.like_normal_pressed);
            holder.likNumTV.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
        } else {
            Drawable drawable = mContext.getResources().getDrawable(R.drawable.community_like);
            holder.likNumTV.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
        }
        holder.likNumTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bean.isLiked) {
                    return;
                }
                User user = LoginManager.getInstance().getUser();
                if (user == null) {
                    LoginActivity.startActivity(mContext);
                    return;
                }
                bean.likenum += 1;
                LikeManager.getInstance().add(bean.id);
                bean.isLiked = true;
                Drawable drawable = mContext.getResources().getDrawable(R.drawable.like_large_pressed);
                holder.likNumTV.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
                holder.likNumTV.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        notifyDataSetChanged();
                    }
                }, 150);
                if (mLikeListener != null) {
                    mLikeListener.onLike(bean.id);
                }
            }
        });

        if (!TextUtils.isEmpty(name)) {
            holder.nicknameTV.setText(name);
            holder.nicknameTV.setVisibility(View.VISIBLE);
        } else {
            holder.nicknameTV.setVisibility(View.GONE);
        }

        if (contentimages != null) {
            initInfoImages(holder.imagesGV, holder.mAdapter, contentimages);

            holder.imagesGV.setVisibility(View.VISIBLE);
        } else {
            holder.imagesGV.setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(time)) {
            holder.timeTV.setText(FormatUtils.getDescriptionTimeFromDateString(time));
        }

        if (!TextUtils.isEmpty(content)) {
            holder.contentTV.setText(content);
            Linkify.addLinks(holder.contentTV, Linkify.WEB_URLS);
            holder.contentTV.setVisibility(View.VISIBLE);
        } else {
            holder.contentTV.setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(headpath)) {
            holder.userPhotoIV.setVisibility(View.VISIBLE);
            Glide.with(mContext).load(headpath).placeholder(R.drawable.cover_default_square).transform(new GlideCircleTransform(mContext)).into(holder.userPhotoIV);
        } else {
            holder.userPhotoIV.setVisibility(View.GONE);
        }
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommunityDetailActivity.startActivity(mContext, bean);
            }
        });
        return convertView;
    }

    private void initInfoImages(ScrollGridView imageGridView, final CommunityGridViewAdapter adapter, final ArrayList<String> imgspaths) {
        int itemWidth = wh;
        int itemHeight = wh;
        int gridViewHeight = 0;

        int gridViewWidth = 0;
        switch (imgspaths.size()) {
            case 1:
                gridViewWidth = 3 * wh + ScreenUtils.dpToPxInt(5) * 2;
                gridViewHeight = gridViewWidth * 1 / 2;
                imageGridView.setNumColumns(1);
                itemWidth = gridViewWidth;
                itemHeight = gridViewWidth * 1 / 2;
                break;
            case 2:
                gridViewHeight = wh;
                gridViewWidth = 2 * wh + ScreenUtils.dpToPxInt(5);
                imageGridView.setNumColumns(2);
                break;
            case 4:
                gridViewWidth = 2 * wh + ScreenUtils.dpToPxInt(5);
                gridViewHeight = gridViewWidth;
                imageGridView.setNumColumns(2);
                break;
            case 3:
                gridViewWidth = wh * 3 + ScreenUtils.dpToPxInt(5) * 2;
                gridViewHeight = wh;
                imageGridView.setNumColumns(3);
                break;
            case 5:
            case 6:
                gridViewWidth = wh * 3 + ScreenUtils.dpToPxInt(5) * 2;
                gridViewHeight = 2 * wh + ScreenUtils.dpToPxInt(5);
                imageGridView.setNumColumns(3);
                break;
            default:
                gridViewWidth = wh * 3 + ScreenUtils.dpToPxInt(5) * 2;
                gridViewHeight = 2 * wh + ScreenUtils.dpToPxInt(5);
                imageGridView.setNumColumns(3);
                break;

        }

        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) imageGridView.getLayoutParams();
        lp.width = gridViewWidth;
        lp.height = gridViewHeight;
        imageGridView.setLayoutParams(lp);

        adapter.updateData(imgspaths, itemWidth, itemHeight);
        if (mFragment != null) {
            imageGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                    PhotoPreview.builder()
                            .setShowDeleteButton(false)
                            .setPhotos(imgspaths)
                            .setCurrentItem(arg2)
                            .start(mContext, mFragment);
//					CommunityDetailActivity.startActivity(mContext,adapter.getItem(arg2));
//					Toast.makeText(mContext, "选择了"+adapter.getItem(arg2)+"图片", Toast.LENGTH_LONG).show();
//					Toast.makeText(mContext, "选择了"+(arg2+1)+"图片", Toast.LENGTH_LONG).show();
                }
            });
        } else {
            imageGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                    PhotoPreview.builder()
                            .setShowDeleteButton(false)
                            .setPhotos(imgspaths)
                            .setCurrentItem(arg2)
                            .start(mActivity);
//					CommunityDetailActivity.startActivity(mContext,adapter.getItem(arg2));
//					Toast.makeText(mContext, "选择了"+adapter.getItem(arg2)+"图片", Toast.LENGTH_LONG).show();
//					Toast.makeText(mContext, "选择了"+(arg2+1)+"图片", Toast.LENGTH_LONG).show();
                }
            });
        }


    }

    public interface LikeListener {
        void onLike(String id);
    }

    class ViewHolder {
        TextView likNumTV;
        TextView commentNumTV;
        ImageView userPhotoIV;
        TextView nicknameTV;
        TextView timeTV;
        TextView contentTV;
        ScrollGridView imagesGV;
        TagGroup tagGroup;
        CommunityGridViewAdapter mAdapter;

        public void bindAdapter() {
            mAdapter = new CommunityGridViewAdapter(mContext);
            imagesGV.setAdapter(mAdapter);
        }
    }


}
